package com.example.lenovo.asia5b.commodity.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.adapter.ClassifyMainSonAdapter;
import com.example.lenovo.asia5b.commodity.bean.ClassifyMainSonBean;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.PullToRefreshLayout;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.Setting;

import static com.wushi.lenovo.asia5b.R.drawable.icon_ascending;
import static com.wushi.lenovo.asia5b.R.drawable.icon_descending;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;

/**
 * 分类第二级
 * Created by lenovo on 2017/7/19.
 */

public class ClassifyMainSonActivity extends BaseActivity implements ICallBack, PullToRefreshLayout.OnRefreshListener {
    private ListView lv_search;
    private ClassifyMainSonAdapter adapter;
    private LoadingDalog loadingDalog;
    private int page = 1;
    private int countPage = 0;
    private PullToRefreshLayout pullToRefreshLayout;
    private List<ClassifyMainSonBean> lists = null;
    private String catid ="";

    //标题
    private List<TextView> tits = new ArrayList<TextView>();
    //横线
    private List<TextView> stripings = new ArrayList<TextView>();
    //排序字段
    private String sortfield = "price";
    // 当前选中
    public int currentIndex;
    //0：倒序，1：顺序；默认为1
    private String sorttype = "1";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify_main_son);
        initView();
        searchData();
    }

    public void initView() {
        if (getIntent().hasExtra("catid")){
            catid = getIntent().getStringExtra("catid");
            String catname = getIntent().getStringExtra("catname");
            F.id(R.id.public_title_name).text(catname);
        }
        loadingDalog = new LoadingDalog(this);
        loadingDalog.show();
        F.id(R.id.btn_change_information).clicked(this);
        F.id(R.id.public_title_name).visibility(View.VISIBLE);
        pullToRefreshLayout = ((PullToRefreshLayout) findViewById(R.id.refresh_view));
        pullToRefreshLayout.setOnRefreshListener(this);
        F.id(public_btn_left).clicked(this);
        lv_search = (ListView) findViewById(R.id.lv_search);
        adapter = new ClassifyMainSonAdapter(this);
        lv_search.setAdapter(adapter);
        lv_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(ClassifyMainSonActivity.this, CommodityDetActivity.class);
                intent.putExtra("goods_id", adapter.getLists().get(i).goods_id);
                startActivity(intent);
            }
        });
        lv_search.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        if (page < countPage) {
                            page += 1;
                            searchData();
                        } else {
                            TextView load_tv = (TextView) findViewById(R.id.load_tv);
                            load_tv.setText(getResources().getString(R.string.no_more_data));
                            load_tv.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
        tits.add(F.id(R.id.txt_price).getTextView());
        tits.add(F.id(R.id.txt_popularity).getTextView());
        tits.add(F.id(R.id.txt_sales).getTextView());
        tits.add(F.id(R.id.txt_overal).getTextView());
        for (int i = 0; i < tits.size(); i++) {
            tits.get(i).setOnClickListener(this);
            //判断当前控件是否被选中
            tits.get(i).setTag(false);
        }
        //先默认第一个被选中
        tits.get(0).setTag(true);
        stripings.add(F.id(R.id.txt_one).getTextView());
        stripings.add(F.id(R.id.txt_two).getTextView());
        stripings.add(F.id(R.id.txt_three).getTextView());
        stripings.add(F.id(R.id.txt_four).getTextView());
    }

    /**
     * 获取单个分类列表数据
     */
    public void searchData() {
        //分类id
        String catid = this.catid;
        //排序字段
        String sortfield = this.sortfield;
        //排序类型
        String sorttype = this.sorttype;
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.CAT_GOODS;
            parmaMap.put("catid", catid);
            parmaMap.put("sortfield", sortfield);
            parmaMap.put("sorttype", sorttype);
            parmaMap.put("page", "" + page);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        } catch (Exception e) {
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case public_btn_left:
                finish();
                break;
            case R.id.txt_overal:
                sortfield = "overall";
                boolean isSelect = (Boolean) tits.get(3).getTag();
                if (isSelect) {
                    tits.get(3).setTag(false);
                    sorttype = "0";
                } else {
                    changBootUI(3);
                    sorttype = "1";
                }
                page = 1;
                searchData();
                break;
            case R.id.txt_popularity:
                sortfield = "popularity";
                boolean isSelect1 = (Boolean) tits.get(1).getTag();
                if (isSelect1) {
                    tits.get(1).setTag(false);
                    sorttype = "0";
                } else {
                    changBootUI(1);
                    sorttype = "1";
                }
                page = 1;
                searchData();
                break;
            case R.id.txt_sales:
                sortfield = "sales";
                boolean isSelect2 = (Boolean) tits.get(2).getTag();
                if (isSelect2) {
                    tits.get(2).setTag(false);
                    sorttype = "0";
                } else {
                    changBootUI(2);
                    sorttype = "1";
                }
                page = 1;
                searchData();
                break;
            case R.id.txt_price:
                sortfield = "price";
                boolean isSelect3 = (Boolean) tits.get(0).getTag();
                if (isSelect3) {
                    tits.get(0).setTag(false);
                    sorttype = "1";
                    Drawable drawable= getResources().getDrawable(icon_ascending);
                    /// 这一步必须要做,否则不会显示.
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    F.id(R.id.txt_price).getTextView().setCompoundDrawables(drawable,null,null,null);
                } else {
                    changBootUI(0);
                    sorttype = "0";
                    Drawable drawable= getResources().getDrawable(icon_descending);
                    /// 这一步必须要做,否则不会显示.
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    F.id(R.id.txt_price).getTextView().setCompoundDrawables(drawable,null,null,null);
                }
                page = 1;
                searchData();
                break;
            default:
                break;

        }
    }

    /**
     * 向下刷新
     */
    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        loadingDalog.show();
        page = 1;
        searchData();
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONObject paging = json.getJSONObject("paging");
                            if (null != paging.getString("page") && "1".equals(paging.getString("page"))) {
                                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                                initPaging(paging);
                                JSONArray goods = json.getJSONArray("goods");
                                lists = Logic.getListToBean(goods, new ClassifyMainSonBean());
                                adapter.setLists(lists);
                                adapter.notifyDataSetChanged();
                            } else if (null != paging.getString("page") && !"1".equals(paging.getString("page"))) {
                                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                                JSONArray goods = (JSONArray) json.get("goods");
                                if (null != goods && goods.length() > 0) {
                                    List<ClassifyMainSonBean> listBean = Logic.getListToBean(goods, new ClassifyMainSonBean());
                                    for (int i = 0; i < listBean.size(); i++) {
                                        lists.add(listBean.get(i));
                                    }
                                    adapter.setLists(lists);
                                    adapter.notifyDataSetChanged();
                                } else {
                                    page = page - 1;
                                }

                            }
                        } else if (state == 1) {
                            U.Toast(ClassifyMainSonActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(ClassifyMainSonActivity.this, getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
            }
            if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                        } else if (state == 1) {
                            U.Toast(ClassifyMainSonActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(ClassifyMainSonActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(ClassifyMainSonActivity.this, getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(ClassifyMainSonActivity.this,getResources().getString(R.string.mysj));
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
    };


    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }


    /**
     * 向上加载
     */
    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }

    public void initPaging(JSONObject json) throws JSONException {
        String pageSizeString = json.getString("count");
        String countPageString = json.getString("countpage");
        String pageString = json.getString("page");
        if (pageSizeString != null && countPageString != null && pageString != null) {
            countPage = Integer.parseInt(countPageString);
            if (countPage <= 1) {
                pullToRefreshLayout.stopLoadMore();
            }
        }
    }

    // 重置按钮,
    public void changBootUI(int selectId) {
        for (int i = 0; i < tits.size(); i++) {
            tits.get(i).setTextColor(ContextCompat.getColor(ClassifyMainSonActivity.this, R.color.my_333));
            stripings.get(i).setVisibility(View.INVISIBLE);
            tits.get(i).setTag(false);
        }
        tits.get(selectId).setTextColor(ContextCompat.getColor(ClassifyMainSonActivity.this, R.color.wathet2));
        stripings.get(selectId).setVisibility(View.VISIBLE);
        tits.get(selectId).setTag(true);
    }
}